package com.mango.leet.code.easy;

import com.mango.data.structure.binarytree.linknode.TreeNode;

/**
 * @Author: mango
 * @Date: 2022/4/11 9:26 下午
 */
public class LC110_BalancedBinaryTree {
    class Solution {
        public boolean isBalanced(TreeNode node) {
            return getInfo(node).isBalance;
        }

        // 递归手机信息
        public Info getInfo(TreeNode node) {
            if (node == null) {
                return new Info(0, true);
            }
            // 搜集左树信息
            Info leftInfo = getInfo(node.left);
            // 搜集右树信息
            Info rightInfo = getInfo(node.right);

            // 高度等于左树和右树高的那个+1
            int height = Math.max(leftInfo.height, rightInfo.height) + 1;
            // 是否平衡等于左右都平衡且高度相差不超过2
            boolean isBalance = leftInfo.isBalance && rightInfo.isBalance
                    && Math.abs(leftInfo.height - rightInfo.height) < 2;

            return new Info(height, isBalance);
        }
    }
}

// 信息体
class Info {
    public int height;
    public boolean isBalance;

    public Info(int height, boolean isBalance) {
        this.height = height;
        this.isBalance = isBalance;
    }
}

